<template>
  <div class="aq-amap-box" :style="{ height: props.height + 'px' }">
    <div v-if="defaultPosition.length==0" class="aq-amap-search">
      <!-- 方式一直接下拉展示 -->
      <!-- <el-select
				style="flex: 1"
				v-model="searchVal"
				filterable
				clearable
				remote
				placeholder="请输入"
				:remote-method="remoteMethod"
				@change="selectChange"
			>
				<el-option v-for="item in searchOptions" :key="item.value" :label="item.label" :value="item.value" />
			</el-select> -->
      <!-- 方式二点击搜索展示 -->
      <el-input
        v-if="isPosition"
        v-model="positionVal"
        placeholder="输入经纬度,例如'104.06677, 30.653135'"
        :prefix-icon="Search"
        clearable
      />
      <el-input
        v-else
        v-model="searchVal"
        placeholder="搜索公司、单位、商户等地点"
        :prefix-icon="Search"
        clearable
      />
      <el-button type="primary" style="margin-left: 10px" @click="searchBtn"
        >搜索</el-button
      >
      <span
        style="display: inline-block; width: 100px; cursor: pointer"
        @click="isPosition = !isPosition"
        >{{ isPosition ? "输入地点" : "输入经纬度" }}</span
      >
    </div>
    <div class="aq-amap-content">
      <!-- <div class="aq-amap-content-search">
				<div id="panel"></div>
			</div> -->
      <div id="mapContainer"></div>
    </div>
    <div class="aq-amap-address">{{ mapAddress }}</div>
  </div>
</template>

<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import { Search } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
/* 是否录入经纬度 */
const isPosition = ref(false);
//emit声明
const emit = defineEmits(["position"]);
const props = defineProps({
  height: {
    type: Number,
    default: 500,
  },
  defaultPosition: {
    type: Array,
    default: () => {
      return [];
    },
  },
  reShow:{
    type:Array,
    default: () => {
      return [];
    },
  }
});
let searchVal = ref("");
let positionVal = ref("");
let searchOptions = ref([]);
let mapAddress = ref("");
let AMaps = ref(null);
let maps = ref(null);
let geocoder = ref(null);
let placeSearch = ref(null);
const markerList = ref([]);
const initMap = () => {
  AMapLoader.load({
    key: "2faaca36dc73b043479bb59b21e697fc",
    version: "2.0",
    plugins: [
      "AMap.Autocomplete",
      "AMap.PlaceSearch",
      "AMap.Scale",
      "AMap.OverView",
      "AMap.ToolBar",
      "AMap.MapType",
      "AMap.PolyEditor",
      "AMap.CircleEditor",
      "AMap.Geolocation",
      "AMap.Heatmap",
      "AMap.DistrictLayer",
      "AMap.HawkEye",
      "AMap.Geocoder",
      "AMap.DistrictSearch",
      "AMap.MouseTool",
    ],
  })
    .then((AMap) => {
      AMaps.value = AMap;
      maps.value = new AMap.Map("mapContainer", {
        resizeEnable: true, //调整大小启用
        viewMode: "3D", //是否为3D地图模式
        zoom: 10, //初始化地图级别
        center: props.defaultPosition.length===2?props.defaultPosition:[104.06677, 30.653135], //初始化地图中心点位置
      });
      var mousetool = new AMap.MouseTool(maps.value);
      mousetool.marker({});
      //Amap draw事件
      mousetool.on("draw", function (e) {
        let obj = {
          value: [e.obj._position.lng,e.obj._position.lat],
          label: "选中位置",
        };
        // console.log("选中位置",e.obj);
        
        emit("position", obj);
      });      
      
      if(props.defaultPosition.length==2){
        new AMap.Marker({
          position: props.defaultPosition,
          map: maps.value
        })
      }
      if(props.reShow.length===2){
        // console.log(888888,props.reShow);
        
        new AMap.Marker({
          position: props.reShow,
          map: maps.value
        })
      }
      // 标记点
      //   const marker = new AMap.Marker({
      //   	position: markerPosition,
      //   	map: maps.value
      //   });
      //   const marker = markerList
      // markerList.value.push(new AMap.Marker({
      // position: [99,33],
      // map: maps.value
      // }))
      // 地址
      geocoder.value = new AMap.Geocoder({
        city: "全国",
      });
      // 搜索
      placeSearch.value = new AMap.PlaceSearch({
        citylimit: true,
        pageSize: 1, // 每页显示结果数量
        pageIndex: 1, // 当前页码
        city: "", // 指定搜索城市，留空表示全国搜索
        map: maps.value, // 绑定地图实例
        // panel: 'panel' // 结果列表DOM容器的ID
      });
    })
    .catch((e) => {
      console.log(e);
    });
};
onMounted(() => {
  initMap();
});

//判断经纬度是否正确及国内
const isTruelyPosition = (code) => {
  if (code.length !== 2) {
    ElMessage.warning("请输入正确的经纬度");
    return false;
  }
  if (
    code[0] < 73.66 ||
    code[0] > 135.05 ||
    code[1] < 3.86 ||
    code[1] > 53.55
  ) {
    ElMessage.warning("请输入正确的经纬度");
    return false;
  }
  return true;
};
/* 通过经纬度获取地址信息 */
const positionChange = async (code) => {
  let lngLat = code.split(",");
  if (isTruelyPosition(lngLat)) {
    let resultObj = await getAddress(lngLat);
    searchFun(resultObj.formattedAddress);
  }
};

// 通过经纬度获取地址
const getAddress = (code) => {
  return new Promise((resolve, reject) => {
    geocoder.value.getAddress(code, (status, result) => {
      // console.log('通过经纬度拿到的地址', result);
      if (status === "complete" && result.info === "OK") {
        resolve(result.regeocode);
      } else {
        reject();
      }
    });
  });
};
// 搜索
let timer = null;
const remoteMethod = (query) => {
  if (!query) return;
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(() => {
    searchOptions.value = [];
    searchFun(query);
  }, 500);
};
const searchFun = (query) => {
  console.log("搜索地址", placeSearch.value);
  placeSearch.value.search(query, async (status, result) => {
    // console.log('搜索结果', result);
    if (status === "complete" && result.info === "OK") {
      // 处理搜索结果-远程搜索下拉才用这个
      for (const item of result.poiList.pois) {
        let lngLat = [item.location.lng, item.location.lat];
        let resultObj = await getAddress(lngLat);
        let obj = {
          value: lngLat,
          label:
            item.name +
            " " +
            resultObj.addressComponent.province +
            resultObj.addressComponent.city +
            resultObj.addressComponent.district,
        };
        searchOptions.value.push(obj);

        emit("position", obj);
      }
    } else {
      // 处理搜索失败
      ElMessage.warning("搜索地址查询失败");
    }
  });
};
const searchBtn = () => {
  //地点搜索
  if (!isPosition.value) {
    if (!searchVal.value) {
      ElMessage.warning("请输入搜索信息");
      return;
    }
    searchFun(searchVal.value);
  } else {
    //经纬度搜索
    if (!positionVal.value) {
      ElMessage.warning("请输入搜索信息");
      return;
    }
    positionChange(positionVal.value);
  }
};
// const selectChange = () => {
//   // 标记
//   const marker = new AMaps.value.Marker({
// 		position: searchVal.value,
// 		map: maps.value
// 	});
//   if (!searchVal.value) {
//     maps.value.setCenter(lnglat);
//     maps.value.setZoom(10);
//   } else {
//     maps.value.setCenter(searchVal.value);
//     maps.value.setZoom(9);
//   }
// };
</script>

<style lang="scss">
.aq-amap-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .aq-amap-search {
    display: flex;
    align-items: center;
  }
  .aq-amap-content {
    position: relative;
    width: 100%;
    flex: 1;
    margin: 10px 0;
    box-sizing: border-box;
    overflow: hidden;
  }
  .aq-amap-content-search {
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 9999;
    display: flex;
    align-items: center;
    #panel {
      width: 250px;
      .amap_lib_placeSearch {
        min-width: 200px !important;
      }
    }
  }
  #mapContainer {
    width: 100%;
    height: 100%;
    // min-height: 300px;
  }
  .aq-amap-address {
    font-size: 14px;
  }
}
</style>
